﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using vCrossPost.PingFM;
using WindowsLive.Writer.Api;

namespace vCrossPost
{
    [WriterPlugin("{8B4348E4-49CF-4d90-AE6C-DBE5503E029F}", "vCrossPost",
        HasEditableOptions = true, ImagePath = "vCrossPost.png")]
    public class CrossPost : PublishNotificationHook
    {
        public const string API_KEY = "bc965dfba1c064d55bf3d782c1e4c09c";

        public string UserKey
        {
            get { return Options.GetString("UserKey", string.Empty); }
            set { Options.SetString("UserKey", value); }
        }

        public string Service
        {
            get { return Options.GetString("Service", string.Empty); }
            set { Options.SetString("Service", value); }
        }

        public override void EditOptions(IWin32Window dialogOwner)
        {
            using (var frmOptions = new FrmOptions(IsValidUserKey, GetServices))
            {
                frmOptions.UserKey = UserKey;
                frmOptions.Service = Service;

                if (frmOptions.ShowDialog(dialogOwner) == DialogResult.OK)
                {
                    UserKey = frmOptions.UserKey;
                    Service = frmOptions.Service;
                }
            }
        }

        public override void OnPostPublish(IWin32Window dialogOwner, IProperties properties,
            IPublishingContext publishingContext, bool publish)
        {
            if (!publish) // Posting draft
                return;

            if (properties.GetBoolean("vCrossPost_Posted", false)) // Post already cross posted
                return;

            var post = publishingContext.PostInfo;
            var body = FixRelativeUrls(publishingContext.HomepageUrl, post.Contents);

            var msg = new PostMessage
            {
                Body = body,
                Service = Service,
                Title = post.Title,
                Method = PostMethods.Blog,
            };

            var api = new Api(API_KEY, UserKey);
            api.Post(msg);

            properties.SetBoolean("vCrossPost_Posted", true);
        }

        protected virtual IDictionary<string, string> GetServices(string userKey)
        {
            var result = new Dictionary<string, string>
            {
                {string.Empty, Properties.Resources.DefaultService}
            };

            var services = new Api(API_KEY, userKey).GetUserServices();

            if (services != null && services.Count > 0)
            {
                foreach (var service in services)
                    result.Add(service.ID, service.Name);
            }

            return result;
        }

        protected virtual bool IsValidUserKey(string userKey)
        {
            return new Api(API_KEY, userKey).Validate();
        }

        // Stolen from XPollinate source (http://xpollinate.codeplex.com/)
        private static string FixRelativeUrls(string targetBlogHomePageUrl, string contents)
        {
            var baseUri = new Uri(targetBlogHomePageUrl).GetLeftPart(UriPartial.Authority);

            var result = contents.Replace("href=\"/", "href=\"" + baseUri + "/");
            return result.Replace("src=\"/", "src=\"" + baseUri + "/");
        }
    }
}